<route lang="yaml">
  meta:
    title: 仓内加工
  </route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'

// 拆分结果项接口
interface SplitResultItem {
  newProductId: string
  productType: string // 新增字段
  productName: string // 原newProductName改为productName
  splitQuantity: number
  targetLocation: string
}
const splitItems = ref<SplitResultItem[]>([])
function handleDeleteSplitItem(index: number) {
  splitItems.value.splice(index, 1)
}

// 添加商品相关状态
const selectedProduct = ref('')
const productOptions = computed(() => [
  {
    label: '智能手机',
    value: 'A001',
    category: 'electronics', // 新增分类字段
  },
  {
    label: '笔记本电脑',
    value: 'B002',
    category: 'electronics',
  },
  {
    label: '洗发水',
    value: 'C003',
    category: 'daily',
  },
])
// 1. 新增类型选项
const typeOptions = ref([
  { label: '电子产品', value: 'electronics' },
  { label: '日用品', value: 'daily' },
  { label: '服装', value: 'clothing' },
])
// 拆分源数据接口
// interface SplitSource {
//   sourceItem: InventoryItem // 源库存项
//   splitQuantity: number // 拆分数量
// }
// 拆分弹窗控制
const splitDialogVisible = ref(false)
// 源库存选择（单选）
const selectedSourceItem = ref<InventoryItem | null>(null)

// 当前编辑的拆分数量
const currentSplitQty = ref(0)
// 用户选择的库位
const selectedTargetLocation = ref('')
// 添加拆分项
function addSplitItem() {
  if (!selectedSourceItem.value) {
    ElMessage.warning('请先选择要拆分的源库存')
    return
  }

  if (currentSplitQty.value <= 0) {
    ElMessage.warning('拆分数量必须大于0')
    return
  }

  splitItems.value.push({
    newProductId: `SPLIT_${Date.now()}`,
    productType: '', // 初始为空
    productName: '', // 初始为空
    splitQuantity: currentSplitQty.value,
    targetLocation: selectedTargetLocation.value,
  })

  currentSplitQty.value = 0
}

// 提交拆分操作
function submitSplit() {
  if (!selectedSourceItem.value) {
    ElMessage.warning('请选择要拆分的源库存')
    return
  }

  const totalSplit = splitItems.value.reduce((sum, item) => sum + item.splitQuantity, 0)
  if (totalSplit > selectedSourceItem.value.quantity) {
    ElMessage.error('拆分总数不能超过源库存数量')
    return
  }

  ElMessage.success(`成功拆分 ${totalSplit} 件商品`)
  splitDialogVisible.value = false
}

// 来源数据表格
const sourceData = ref<InventoryItem[]>([
  { id: 'INV001', warehouseName: '中心仓', locationName: 'A区-货架1层', productName: '零件A', quantity: 50 },
  { id: 'INV002', warehouseName: '中心仓', locationName: 'B区-货架2层', productName: '零件B', quantity: 30 },
  { id: 'INV003', warehouseName: '分仓1号', locationName: 'C区-货架3层', productName: '零件C', quantity: 20 },
])
// 所有可用库位选项（用于下拉框）
// 显式指定类型
const locationOptions = computed(() => {
  const locations = sourceData.value.map((i: InventoryItem) => i.locationName)
  return [...new Set(locations)].map(loc => ({
    label: loc,
    value: loc,
  }))
})
// 来源库存数据接口
interface InventoryItem {
  id: string
  warehouseName: string
  locationName: string
  productName: string
  quantity: number
  editableQuantity?: number // 添加可选属性
}

// 组合结果接口
interface CombinedResult {
  newProductId: string // 新商品编号
  newProductName: string // 新商品名称
  totalQuantity: number // 组合后的总数量
}

// 弹窗控制
const combineDialogVisible = ref(false)

// 筛选条件
const selectedWarehouse = ref('')
const selectedLocation = ref('')

// 已选数据
const selectedItems = ref<InventoryItem[]>([])

// 结果数据（初始化为空对象）
const combinedResult = ref<CombinedResult | null>(null)

// 计算属性：筛选后的来源数据
const filteredSourceData = computed(() => {
  return sourceData.value.filter((item) => {
    const matchWarehouse = !selectedWarehouse.value || item.warehouseName === selectedWarehouse.value
    const matchLocation = !selectedLocation.value || item.locationName === selectedLocation.value
    return matchWarehouse && matchLocation
  })
})

// 多选处理
function handleSelectionChange(val: InventoryItem[]) {
  selectedItems.value = val
  updateCombinedResult()
}

// 更新组合结果
// 修改updateCombinedResult方法
function updateCombinedResult() {
  if (selectedItems.value.length === 0) {
    combinedResult.value = null
    return
  }

  const totalQty = selectedItems.value.reduce((sum, item) => {
    const qty = item.editableQuantity ?? 0
    return sum + qty
  }, 0)

  combinedResult.value = {
    newProductId: `COM${Date.now()}`,
    newProductName: '组合商品',
    totalQuantity: totalQty,
  }
}

// 提交组合操作
function submitCombination() {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条来源数据')
    return
  }

  if (!combinedResult.value) {
    ElMessage.error('组合信息异常，请刷新页面重试')
    return
  }

  ElMessage.success(`成功组合 ${combinedResult.value.totalQuantity} 件 "${combinedResult.value.newProductName}"`)
  combineDialogVisible.value = false
}

// 作业单相关字段和方法（保持不变）

interface ProcessProject {
  id: string // 作业单号
  type: string // 作业类型
  userName: string // 操作人
  status: '待处理' | '进行中' | '已完成' | '已取消' // 操作状态
  createTime: string // 创建时间
}

// 表格数据
const tableData = ref<ProcessProject[]>([
  {
    id: 'PO20240501001',
    type: '拆分加工',
    userName: '张三',
    status: '进行中',
    createTime: '2024-05-01 10:30',
  },
  {
    id: 'PO20240501002',
    type: '组合加工',
    userName: '李四',
    status: '待处理',
    createTime: '2024-05-01 14:20',
  },
  {
    id: 'PO20240502001',
    type: '拆分加工',
    userName: '王五',
    status: '已完成',
    createTime: '2024-05-02 09:15',
  },
])

// 搜索关键词
const searchKeyword = ref('')

// 新增/编辑/删除模拟函数

function handleEdit(row: ProcessProject) {
  ElMessage.info(`确认加工：${row.id}`)
}
async function handleDelete(row: ProcessProject) {
  try {
    await ElMessageBox.confirm(`确定删除作业单【${row.id}】吗？`, '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }
  catch {
    ElMessage.info('已取消删除')
  }
}
function handleDivide() {
  console.warn('拆分操作')
  splitDialogVisible.value = true
  console.warn(splitDialogVisible.value)
}
// 4. 商品筛选逻辑
function filteredProducts(row: SplitResultItem) {
  return productOptions.value.filter((opt) => {
    // 根据实际业务逻辑实现类型过滤
    return opt.category === row.productType
  })
}
function updateProductName() {
  ElMessage.success('更新成功')
}
</script>

<template>
  <div>
    <FaPageMain>
      <!-- 操作栏 -->
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="combineDialogVisible = true">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">组合加工</span>
          </el-button>
          <el-button type="primary" @click="handleDivide">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">拆分加工</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input v-model="searchKeyword" placeholder="请输入作业单据号" clearable style="width: 200px;">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%;" max-height="calc(100vh - 200px)" :fit="true">
          <el-table-column type="selection" />
          <el-table-column prop="id" label="作业单号" />
          <el-table-column prop="type" label="作业类型" />
          <el-table-column prop="userName" label="操作人" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="status" label="操作状态">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === '待处理' ? 'info'
                  : row.status === '进行中' ? 'warning'
                    : row.status === '已完成' ? 'success' : 'danger'
                "
              >
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-button type="primary" link @click="handleEdit(row)">
                  确认加工
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :page-size="20"
          :pager-count="11"
          layout="prev, pager, next"
          :total="tableData.length"
        />
      </div>
    </FaPageMain>

    <!-- 组合加工弹窗 -->
    <el-dialog v-model="combineDialogVisible" title="组合加工" width="1200px">
      <div class="p-4">
        <!-- 筛选项 -->
        <div class="mb-4 flex gap-4">
          <el-select v-model="selectedWarehouse" placeholder="选择仓库" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.warehouseName))]"
              :key="String(item)"
              :label="item"
              :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>

          <el-select v-model="selectedLocation" placeholder="选择库位" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.locationName))]"
              :key="String(item)"
              :label="item"
              :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>
        </div>

        <!-- 来源数据表格 -->
        <h4 class="mb-2">
          来源数据
        </h4>
        <el-table
          :data="filteredSourceData"
          style="width: 100%;"
          :fit="true"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column prop="id" label="库存编号" />
          <el-table-column prop="warehouseName" label="仓库" />
          <el-table-column prop="locationName" label="库位" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column label="操作数量">
            <template #default="{ row }">
              <el-input-number v-model="row.editableQuantity" :min="0" :max="row.quantity" @change="updateCombinedResult" />
            </template>
          </el-table-column>
        </el-table>

        <!-- 结果数据展示 -->
        <div class="mt-6 border rounded bg-gray-50 p-4">
          <h4>组合后结果</h4>
          <div class="grid grid-cols-3 mt-2 gap-4">
            <!-- 新商品名称（输入框） -->
            <div>
              <label class="text-sm text-gray-600">新商品</label>
              <el-select v-model="selectedProduct" placeholder="请选择商品" style="width: 100%;">
                <el-option
                  v-for="item in productOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <!-- 库位选择（下拉框） -->
            <div>
              <label class="text-sm text-gray-600">目标库位</label>
              <el-select v-model="selectedTargetLocation" placeholder="请选择库位" style="width: 100%;">
                <el-option
                  v-for="loc in locationOptions"
                  :key="loc.value"
                  :label="loc.label"
                  :value="loc.value"
                />
              </el-select>
            </div>

            <!-- 组合数量 -->
            <div v-if="combinedResult">
              <label class="text-sm text-gray-600">组合数量</label>
              <p>{{ combinedResult.totalQuantity }} 件</p>
            </div>
            <div v-else>
              <label class="text-sm text-gray-600">组合数量</label>
              <p>—</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="combineDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCombination">确认组合</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 拆分加工弹窗 -->
    <el-dialog v-model="splitDialogVisible" title="拆分加工" width="900px">
      <div class="p-4">
        <!-- 筛选项 -->
        <div class="mb-4 flex gap-4">
          <el-select v-model="selectedWarehouse" placeholder="选择仓库" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.warehouseName))]"
              :key="String(item)"
              :label="item"
              :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>

          <el-select v-model="selectedLocation" placeholder="选择库位" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.locationName))]"
              :key="String(item)"
              :label="item"
              :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>
        </div>
        <!-- 源库存选择 -->
        <div class="mb-4">
          <h4 class="mb-2">
            源库存选择
          </h4>

          <el-table
            :data="filteredSourceData"
            style="width: 100%;"
            @current-change="val => selectedSourceItem = val"
          >
            <el-table-column type="selection" />
            <el-table-column prop="id" label="库存编号" />
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="quantity" label="可用数量" />
          </el-table>
        </div>
        <!-- 拆分项配置 -->
        <div class="border rounded bg-gray-50 p-4">
          <div class="mb-4 flex gap-4">
            <!-- 修改拆分弹窗中的el-input-number组件 -->
            <el-input-number
              v-model="currentSplitQty"
              placeholder="输入拆分数量"
              :min="0"
              :max="selectedSourceItem?.quantity || 0"
              :disabled="!selectedSourceItem"
            />
            <el-button type="primary" @click="addSplitItem">
              添加拆分项
            </el-button>
          </div>

          <el-table :data="splitItems">
            <!-- 商品类型 -->
            <el-table-column label="商品类型">
              <template #default="{ row }">
                <el-select
                  v-model="row.productType"
                  placeholder="选择类型"
                  @change="updateProductName()"
                >
                  <el-option
                    v-for="type in typeOptions"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 商品名称 -->
            <el-table-column label="商品名称">
              <template #default="{ row }">
                <el-select
                  v-model="row.productName"
                  placeholder="选择商品"
                  :disabled="!row.productType"
                >
                  <el-option
                    v-for="product in filteredProducts(row)"
                    :key="product.value"
                    :label="product.label"
                    :value="product.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 数量 -->
            <el-table-column prop="splitQuantity" label="数量" />

            <!-- 目标库位 -->
            <el-table-column label="目标库位">
              <template #default="{ row }">
                <el-select v-model="row.targetLocation">
                  <el-option
                    v-for="loc in locationOptions"
                    :key="loc.value"
                    :label="loc.label"
                    :value="loc.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 删除操作 -->
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  link
                  @click="handleDeleteSplitItem($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="splitDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitSplit">
          确认拆分
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

  <style scoped>
  .search-wrapper {
    display: flex;
    gap: 12px;
  }

  .table-wrapper {
    margin-top: 16px;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
  </style>
